package cn.thoughtworks.school.services;

import cn.thoughtworks.school.entities.Application;
import cn.thoughtworks.school.entities.SerialSubscription;
import cn.thoughtworks.school.entities.VideoSubscription;
import cn.thoughtworks.school.repositories.SerialSubscriptionRepository;
import cn.thoughtworks.school.repositories.VideoSubscriptionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SubscriptionService {
  @Autowired
  private SerialSubscriptionRepository serialSubscriptionRepository;
  @Autowired
  private VideoSubscriptionRepository videoSubscriptionRepository;

  public Boolean isUserSubscribeSerial(Long userId, Long serialId) {
    return !serialSubscriptionRepository.findByUserIdAndSerialId(userId, serialId).isPresent();
  }

  public void create(Long authorizerId, Application application) {
    if ("serial".equals(application.getType())) {
      serialSubscriptionRepository.save(SerialSubscription.build(authorizerId, application));
    }
    if ("video".equals(application.getType())) {
      videoSubscriptionRepository.save(VideoSubscription.build(authorizerId, application));
    }
  }

  public boolean isUserSubscribeVideo(Long userId, Long videoId) {
    return !videoSubscriptionRepository.findByUserIdAndVideoId(userId, videoId).isPresent();
  }
}
